using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;
using System.Text.Json;
using System.IO;

namespace DocumentCreationSystem;

/// <summary>
/// AI配置测试程序
/// </summary>
public class TestAIConfig
{
    public static async Task Main(string[] args)
    {
        // 设置服务
        var services = new ServiceCollection();
        services.AddLogging(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Debug));
        services.AddHttpClient();
        
        // 添加配置
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false)
            .Build();
        services.AddSingleton<IConfiguration>(configuration);
        
        // 添加AI配置服务
        services.AddScoped<IAIModelConfigService, AIModelConfigService>();
        
        var serviceProvider = services.BuildServiceProvider();
        var logger = serviceProvider.GetRequiredService<ILogger<TestAIConfig>>();
        var configService = serviceProvider.GetRequiredService<IAIModelConfigService>();

        try
        {
            logger.LogInformation("=== AI配置测试开始 ===");
            
            // 1. 测试获取当前配置
            logger.LogInformation("1. 获取当前配置...");
            var currentConfig = await configService.GetConfigAsync();
            logger.LogInformation($"当前平台: {currentConfig.Platform}");
            logger.LogInformation($"Ollama选中模型: {currentConfig.OllamaConfig?.SelectedModel ?? "无"}");
            logger.LogInformation($"LMStudio选中模型: {currentConfig.LMStudioConfig?.SelectedModel ?? "无"}");
            logger.LogInformation($"智谱AI模型: {currentConfig.ZhipuAIConfig?.Model ?? "无"}");
            logger.LogInformation($"DeepSeek模型: {currentConfig.DeepSeekConfig?.Model ?? "无"}");
            
            // 2. 测试保存新配置
            logger.LogInformation("\n2. 测试保存LM Studio配置...");
            var testConfig = new AIModelConfig
            {
                Platform = "LMStudio",
                Temperature = 0.8f,
                MaxTokens = 4000,
                EnableThinkingChain = true,
                Timeout = 60,
                OllamaConfig = new OllamaConfig
                {
                    BaseUrl = "http://localhost:11434",
                    SelectedModel = "llama3.2:latest"
                },
                LMStudioConfig = new LMStudioConfig
                {
                    BaseUrl = "http://localhost:1234",
                    SelectedModel = "test-model"
                },
                ZhipuAIConfig = new ZhipuAIConfig
                {
                    ApiKey = "test-key",
                    BaseUrl = "https://open.bigmodel.cn/api/paas/v4",
                    Model = "GLM-4-Flash-250414"
                },
                DeepSeekConfig = new DeepSeekConfig
                {
                    ApiKey = "test-deepseek-key",
                    BaseUrl = "https://api.deepseek.com",
                    Model = "deepseek-chat"
                }
            };
            
            await configService.SaveConfigAsync(testConfig);
            logger.LogInformation("配置保存完成");
            
            // 3. 重新读取配置验证
            logger.LogInformation("\n3. 重新读取配置验证...");
            var reloadedConfig = await configService.GetConfigAsync();
            logger.LogInformation($"重新加载的平台: {reloadedConfig.Platform}");
            logger.LogInformation($"LMStudio选中模型: {reloadedConfig.LMStudioConfig?.SelectedModel ?? "无"}");
            
            // 4. 验证配置是否正确
            if (reloadedConfig.Platform == "LMStudio" && 
                reloadedConfig.LMStudioConfig?.SelectedModel == "test-model")
            {
                logger.LogInformation("✅ 配置保存和加载测试通过");
            }
            else
            {
                logger.LogError("❌ 配置保存和加载测试失败");
                logger.LogError($"期望平台: LMStudio, 实际: {reloadedConfig.Platform}");
                logger.LogError($"期望模型: test-model, 实际: {reloadedConfig.LMStudioConfig?.SelectedModel}");
            }
            
            // 5. 显示配置文件路径
            var configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
                "DocumentCreationSystem", "ai-config.json");
            logger.LogInformation($"\n配置文件路径: {configPath}");
            
            if (File.Exists(configPath))
            {
                var configContent = await File.ReadAllTextAsync(configPath);
                logger.LogInformation("配置文件内容:");
                logger.LogInformation(configContent);
            }
            else
            {
                logger.LogWarning("配置文件不存在");
            }
            
            logger.LogInformation("\n=== AI配置测试完成 ===");
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "测试过程中发生错误");
        }
        
        Console.WriteLine("\n按任意键退出...");
        Console.ReadKey();
    }
}
